<template>
  <div class="">
    <el-container>
      <splitpanel title="分类" icon="company" :department="department" :default-props="defaultProps" @handleNodeClick="handleNodeClick" />
      <el-main class="el-mainBox">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <i class="el-icon-notebook-2 primary" /><span class="primary" style="margin-left: 5px;">{{ reportList.name }}</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="reportTreeShow" v-permission="['report.add']">添加报表</el-button>
          </div>
          <div :class="['text', 'item', lookIsShow? 'bb': '']" style="">
            <el-form ref="sysReportForm" :model="form" label-width="80px" style="display: flex; flex-wrap: wrap; width: 50%;">
              <el-form-item
                v-for="item in reportList.params"
                :key="item.paramName"
                :label="item.title"
                style="width: 50%; margin-bottom: 10px;"
                v-if="item.dataSource !== 0"
              >
                <div v-if="item.dataSource == 1" class="block">
                  <el-date-picker
                    v-model="form[item.paramName]"
                    value-format="yyyy-MM-dd"
                    align="right"
                    type="date"
                    placeholder="选择日期"
                    :picker-options="pickerOptions"
                  />
                </div>
                <el-input v-if="item.dataSource == 2" v-model="nameOptions[item.paramName]" clearable placeholder="请选择部门"
                          suffix-icon="el-icon-arrow-down" @clear="form[item.paramName] = ''" @focus="officeDialogShow(item.paramName)" />
                <el-select v-if="item.dataSource == 3" v-model="form[item.paramName]" clearable placeholder="请选择仓库"
                          @focus="getShop">
                  <el-option v-for="item in shopIdOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
                <el-select v-if="item.dataSource == 4" v-model="form[item.paramName]" clearable placeholder="请选择员工"
                          @focus="employee">
                  <el-option v-for="item in employeeIdOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
                <el-select v-if="item.dataSource == 5" v-model="form[item.paramName]" clearable placeholder="请选择客户"
                          filterable @focus="getMemberList" style="width: 600px;" :filter-method="queryMember">
                    <el-option v-for="item in memberIdOptions" :key="item.value" :label="item.label" :value="item.value">
                      <div style="display: flex">
                        <span style="width: 60px;">{{item.code}}</span>
                        <span style="float: left;width: 100px;overflow: hidden;text-overflow: ellipsis;">{{ item.label }}</span>
                        <span style="float: right; color: #8492a6; font-size: 8px;width: 80px;margin-left: 10px">{{ item.mobile }}</span>
                        <div style="width: 200px;">
                          <span style="color: #8492a6; font-size: 8px;">{{item.address}}</span>
                        </div>
                      </div>
                    </el-option>
                  <div style="display: flex;width: 100%;position: absolute;bottom: 0">
                    <div style="width: 50%;background-color: rgb(248,248,248);"></div>
                      <div class="elOption" @click="toSearchMember">搜索客户</div>
                  </div>
                  <div style="height: 30px"></div>
                </el-select>
                <el-select v-if="item.dataSource == 6" v-model="form[item.paramName]" clearable placeholder="请选择供应商"
                          filterable @focus="getSuppierList(item.paramName)" :filter-method="querySuppier">
                  <el-option v-for="item in suppierIdOptions" :key="item.value" :label="item.label" :value="item.value" >
                    <div style="display: flex">
                      <span style="float: left;width: 80px;overflow: hidden;text-overflow: ellipsis;">{{ item.label }}</span>
                      <span style="width: 100px;overflow: hidden;text-overflow: ellipsis;">{{ item.phone }}</span>
                      <div style="width: 200px;">
                        <span style="color: #8492a6; font-size: 8px;">{{item.areaName}}{{item.address}}</span>
                      </div>
                    </div>
                  </el-option>
                  <div style="display: flex;width: 100%;position: absolute;bottom: 0">
                    <div style="width: 50%;background-color: rgb(248,248,248);"></div>
                    <div class="elOption" @click="toSearchSupplier">搜索供应商</div>
                  </div>
                  <div style="height: 30px"></div>
                </el-select>
                <el-select v-if="item.dataSource == 7" v-model="form[item.paramName]" clearable placeholder="请选择品牌"
                          filterable @focus="getBrandList(item.paramName)" :filter-method="queryBrand">
                  <el-option v-for="item in brandIdOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
                <el-input v-if="item.dataSource == 8" v-model="nameOptions[item.paramName]" clearable placeholder="请选择分类"
                          suffix-icon="el-icon-arrow-down" @clear="form[item.paramName] = ''" @focus="categoryDialogShow(item.paramName)" />
                <el-select v-if="item.dataSource == 9" v-model="form[item.paramName]" clearable placeholder="请选择商品"
                          filterable @focus="getProductList(item.paramName)" :filter-method="queryProduct">
                  <el-option v-for="item in productOptions" style="width:650px" :key="item.value" :label="item.label" :value="item.value" >
                    <div style="display: flex">
                      <span style="width: 80px;overflow: hidden;text-overflow: ellipsis;">{{ item.sn }}</span>
                      <span style="float: left;width: 160px;overflow: hidden;text-overflow: ellipsis;margin-left: 10px">{{ item.label }}</span>
                      <div style="width: 200px;">
                        <span style="color: #8492a6; font-size: 8px;">{{item.spec1}}</span>
                      </div>
                    </div>
                  </el-option>
                  <div style="display: flex;width: 100%;position: absolute;bottom: 0">
                    <div style="width: 50%;background-color: rgb(248,248,248);"></div>
                    <div class="elOption" @click="toAddProduct">搜索商品</div>
                  </div>
                  <div style="height: 30px"></div>
                </el-select>
                <el-select v-if="item.dataSource == 10" v-model="form[item.paramName]" clearable placeholder="单位类型">
                  <el-option :key="1" :label="最小单位" :value="1" />
                  <el-option :key="2" :label="统计单位" :value="2" />
                </el-select>
              </el-form-item>
            </el-form>
            <div style="display: flex; align-items: center; justify-content: center; width: 50%;">
              <el-button :loading="lookClicked" @click="lookReport">预览</el-button>
              <!-- <el-button @click="printFn">打印</el-button> -->
              <el-button :loading="exportClicked" @click="exportFn" v-permission="['report.print']">导出</el-button>
            </div>
          </div>
          <div v-show="lookIsShow" style="margin: 10px 0; height: 660px;">
            <embed :key="time" :src="lookImg" alt="" width="100%" height="100%">
          </div>
        </el-card>
      </el-main>
    </el-container>
    <category-dialog ref="categoryDialog" request="productCategory" @confirm="categoryDialogConfirm" />
    <office-dialog ref="officeDialog" @confirm="officeDialogConfirm" />
    <!-- <member-dialog ref="memberDialog" @confirm="memberDialogConfirm" /> -->
    <el-dialog title="请选择要添加的报表" :visible.sync="reportDialog">
      <el-tree
        ref="selectReport"
        :data="reportTree"
        show-checkbox
        node-key="id"
        :props="reportProps">
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="reportDialog = false">取 消</el-button>
        <el-button :loading="addClicked" type="primary" @click="addReport">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="双击选择客户"
      :visible.sync="memberTableVisible"
      width="950px"
      v-el-drag-dialog
      append-to-body
      :before-close="memberTableClose">
      <div style="position: relative;">
        <member-table @memberDouble="memberDouble" @memberTableClose="memberTableClose"></member-table>
      </div>
    </el-dialog>
    <el-dialog
      title="查找供应商"
      :visible.sync="supplierVisible"
      width="950px"
      v-el-drag-dialog
      append-to-body
      :before-close="supplierClose">
      <div style="position: relative;height: 63vh;overflow: auto">
        <supplierTable  @doubleSupplier="doubleSupplier"></supplierTable>
      </div>
    </el-dialog>
    <el-dialog
      title="新增商品"
      :visible.sync="orderVisible"
      width="950px"
      v-el-drag-dialog
      :before-close="orderClose">
      <div style="position: relative;">
        <productTable ref="productList" @doubleClick="doubleClick" @addClick="addProductClick"></productTable>
      </div>
    </el-dialog>
  </div>
</template>
<style scoped>
  .elOption{
    background-color: #909399;
    color:white ;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 50%;
    height: 40px
  }
.table-container {
  padding: 10px;
  box-sizing: border-box;
}
.el-mainBox {
  padding: 0 !important;
}
.text {
  font-size: 14px;
}

.item {
  /* margin-bottom: 18px; */
  display: flex;
  justify-content: space-between;
  padding-bottom: 10px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: '';
}
.clearfix:after {
  clear: both;
}

.box-card {
  width: 100%;
}
.bb {
  border-bottom: 1px solid #e6ebf5;
}
.el-range-editor.el-input__inner {
    width: 100% !important;
}
.el-select {
  width: 100% !important;
}
.el-input {
  width: 100% !important;
}
</style>
<script>
  import supplierTable from '../../components/SupplierTable/supplierList'
  import memberTable from '@/components/MemberTable/index'
  import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
  import productTable from '@/components/ProductList/productList'
import permission from '@/directive/permission/index.js' // 权限判断指令
import utils from '../../utils/utils.js'
import { nav, list, templateList, add } from '@/api/report'
import { list as employeeList } from '@/api/sysEmployee'
import { list as memberList } from '@/api/member'
import { list as productList } from '@/api/product'
import { list as supplierList } from '@/api/supplier'
import { list as brandList } from '@/api/brand'
import { list as shopList } from '@/api/shop'
import splitpanel from './components/splitpanel.vue'
import CategoryDialog from '@/components/CategoryDialog'
import OfficeDialog from '@/components/OfficeDialog'
import { mapGetters } from 'vuex'
import axios from 'axios'

import printJs from 'print-js';

export default {
  name: 'Report',
  directives: { permission ,elDragDialog},
  components: {
    splitpanel,
    CategoryDialog,
    OfficeDialog,
    productTable,
    memberTable,
    supplierTable
  },
  filters: {},
  data() {
    return {
      lookClicked: false,
      exportClicked: false,
      supplierVisible:false,
      addClicked: false,
      department: [],
      defaultProps: {
        children: 'childrens',
        label: 'name'
      },
      reportList: [],
      form: {},
      orderVisible:false,
      memberTableVisible:false,
      optionKey: '',
      typeOneDisabled: false, // 公司类型是否禁用
      typeTwoDisabled: false, // 部门类型是否禁用
      nameOptions: [], // 用于存储弹窗组件的name
      shopIdOptions: [],
      employeeIdOptions: [],
      memberIdOptions: [],
      suppierIdOptions: [],
      brandIdOptions: [],
      productOptions: [],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        },
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      },
      lookIsShow: false,
      lookImg: '',
      time: null,
      reportDialog: false,
      reportTree: [],
      reportProps: {
        children: 'childrens',
        label: 'name'
      }
    }
  },
  computed: {
    ...mapGetters([
      'token'
    ])
  },
  watch: {

    lookImg() { // img变更时重新刷新页面,避免数据更新页面不更新
      this.$nextTick(() => {
        this.lookIsShow = true
      })
    }
  },
  created() {
    this.loadReport() // 初始化列表
    this.loadTree() // 初始化导航
  },
  methods: {
    doubleSupplier(data){
      this.reportList.params.forEach(item=>{
        if (item.dataSource===6){
          this.form[item.paramName]=data.id
        }
      })
      this.supplierVisible=false
    },
    supplierClose(){
      this.supplierVisible=false
    },
    toSearchSupplier(){

      this.supplierVisible=true
    },
    memberDouble(data){
      this.reportList.params.forEach(item=>{
        if (item.dataSource===5){
          this.form[item.paramName]=data.id
        }
      })
      this.memberTableVisible = false
    },
    memberTableClose(){
      this.memberTableVisible = false
    },
    toSearchMember() {
      this.memberTableVisible = true
    },
    addProductClick(data){
      this.reportList.params.forEach(item=>{
          if (item.dataSource===9){
            this.form[item.paramName]=data[0].id
          }
      })
      if(data.length>1){
        this.orderVisible = false;
        this.$message({
          message: '只能查询一个商品',
          offset: 120,
          center: true
        })
      }else{
        this.orderVisible = false;
      }
    },
    doubleClick(val){
      this.reportList.params.forEach(item=>{
        if (item.dataSource===9){
          this.form[item.paramName]=val.id
        }
      })
      this.orderVisible = false;
    },
    orderClose(){
      this.orderVisible=false
    },
    toAddProduct(){
      this.orderVisible=true
    },
    categoryDialogShow(key) {
      this.optionKey = key
      console.log('点击了'+key)
      this.$refs.categoryDialog.show()
    },
    categoryDialogConfirm(val) {
      this.$set(this.form, this.optionKey, val.id)
      this.$set(this.nameOptions, this.optionKey, val.name)
    },
    officeDialogShow(key) {
      console.log('点击了', key)
      this.optionKey = key
      this.$refs.officeDialog.show()
    },
    officeDialogConfirm(val) {
      console.log(val, 'val')
      // this.form.officeId = val.id
      this.$set(this.form, this.optionKey, val.id)
      this.$set(this.nameOptions, this.optionKey, val.name)
      // this.nameOptions.topName = val.name
      if (val.type == 0) {
        // this.form.type = 1
        this.typeOneDisabled = false
        this.typeTwoDisabled = false
      } else {
        // this.form.type = 1
        this.typeOneDisabled = true
      }
    },
    getShop () { // 获取仓库
      shopList().then(res => {
        res.data.data.forEach((option, index) => {
          const obj = {
            value: option.id,
            label: option.name
          }
          this.$set(this.shopIdOptions, index, obj)
        })
      }).catch(err => {
        console.log(err)
      })
    },
    employee () { // 获取员工
      employeeList().then(res => {
        res.data.data.forEach((option, index) => {
          const obj = {
            value: option.id,
            label: option.name
          }
          this.$set(this.employeeIdOptions, index, obj)
        })
      }).catch(err => {
        console.log(err)
      })
    },
    queryMember (query) { // 搜索客户
      console.log(query)
      this.memberIdOptions = []
      memberList({name: query}).then(res => {
        res.data.data.forEach((option, index) => {
          const obj = {
            mobile:option.mobile,
            address:option.address,
            code:option.code,
            value: option.id,
            label: option.name
          }
          this.$set(this.memberIdOptions, index, obj)
        })
      }).catch(err => {
        console.log(err)
      })
    },
    getMemberList () { // 加载客户
      memberList().then(res => {
        res.data.data.forEach((option, index) => {
          const obj = {
            mobile:option.mobile,
            address:option.address,
            code:option.code,
            value: option.id,
            label: option.name
          }
          this.$set(this.memberIdOptions, index, obj)
        })
      }).catch(err => {
        console.log(err)
      })
    },
    querySuppier (query) { // 查询供应商
      this.suppierIdOptions = []
      supplierList({name: query}).then(res => {
        res.data.data.forEach((option, index) => {
          const obj = {
            phone:option.phone,
            areaName:option.areaName,
            address:option.address,
            value: option.id,
            label: option.name
          }
          this.$set(this.suppierIdOptions, index, obj)
        })
      }).catch(err => {
        console.log(err)
      })
    },
    getSuppierList (data) { // 加载供应商
      console.log(data)
      supplierList().then(res => {
        res.data.data.forEach((option, index) => {
          const obj = {
            phone:option.phone,
            areaName:option.areaName,
            address:option.address,
            value: option.id,
            label: option.name
          }
          this.$set(this.suppierIdOptions, index, obj)
        })
      }).catch(err => {
        console.log(err)
      })
    },
    queryBrand (query) { // 查询品牌
      this.brandIdOptions = []
      brandList({name: query}).then(res => {
        res.data.data.forEach((option, index) => {
          const obj = {
            value: option.id,
            label: option.name
          }
          this.$set(this.brandIdOptions, index, obj)
        })
      }).catch(err => {
        console.log(err)
      })
    },
    getBrandList (data) { // 加载品牌
      console.log(data)
      brandList().then(res => {
        res.data.data.forEach((option, index) => {
          const obj = {
            value: option.id,
            label: option.name
          }
          this.$set(this.brandIdOptions, index, obj)
        })
      }).catch(err => {
        console.log(err)
      })
    },
    queryProduct (query) { // 查询商品
      this.productOptions = []
      productList({name: query}).then(res => {
        res.data.data.forEach((option, index) => {
          const obj = {
            sn:option.sn,
            spec1:option.spec1,
            value: option.id,
            label: option.name
          }
          this.$set(this.productOptions, index, option)
        })
      }).catch(err => {
        console.log(err)
      })
    },
    getProductList (data) { // 加载商品
      console.log(data)
      productList().then(res => {
        res.data.data.forEach((option, index) => {
          const obj = {
            sn:option.sn,
            spec1:option.spec1,
            value: option.id,
            label: option.name
          }
          this.$set(this.productOptions, index, obj)
        })
      }).catch(err => {
        console.log(err)
      })
    },
    getDatrFn(item) {
      if (item.dataSource === 1) { //  // 初始化为当天时间
        const date = new Date()
        const year = date.getFullYear()
        const month = date.getMonth() + 1 + ''
        const day = date.getDate() + ''
        const newDate = `${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`
        this.$set(this.form, item.paramName, '')
        this.form[item.paramName] = newDate
      }
      if (item.dataSource === 10) {
        this.form[item.paramName] = '1'
      }
    },
    loadReport() {
      nav().then(res => {
        const params = new URLSearchParams()
        params.append('reportCategoryId', res.data[0].id)
        list(params).then(response => {
          console.log('data', response)
          if (response.type == 'success') {
            let index = 0
            for (let i = 0; i < response.data.data.length; i++) {
              if (response.data.data[i].status === 0) { // 如果第一个的状态是禁用则不显示,循环,直到可用
                index++
              } else {
                break
              }
            }
            this.reportList = response.data.data[index]
            if (typeof response.data.data[index].params === 'string') {
              this.reportList.params = eval('(' + response.data.data[index].params + ')') // 转成数组
              this.reportList.params.sort((a, b) => { // 排序,始终按key的顺序进行排序,让日期再最前面
                return (a.dataSource - b.dataSource)
              })
              console.log(this.reportList.params)
              this.reportList.params.forEach(item => {
                this.getDatrFn(item) // 拿到所有下拉菜单
              })
            }
          } else {
            this.$message({
              message: response.content,
              offset: 120,
              center: true
            })
          }
        }).catch(error => {
        })
      }).catch(err => {

      })
    },
    loadTree() {
      nav().then(res => {
        // console.log(res)
        this.department = res.data
        res.data.forEach((splitpanelItem, index) => { // 循环分类
          const params = new URLSearchParams()
          params.append('reportCategoryId', splitpanelItem.id)
          list(params).then(response => { // 根据分类id查找对应报表
            console.log('res', response)
            response.data.data.forEach(reportList => { // 循环出对应id的报表
              if (reportList.status !== 0) { // 当前状态为禁用则不添加进分类列表
                this.department[index].childrens.push(reportList)
              }
            })
          })
            .catch(error => {})
        })
      }).catch(err => {
        console.log(err)
      })
    },
    handleNodeClick(data) {
      console.log('data', typeof data.params)
      if (data.reportCategoryId) { // 判断是否为报表,只有是的时候才显示列表
        this.reportList = data
        if (typeof data.params === 'string') { // 如果未转成数组
          this.reportList.params = eval('(' + data.params + ')') // 转成数组
          this.reportList.params.sort((a, b) => { // 排序,始终按key的顺序进行排序,让日期再最前面
            return (a.dataSource - b.dataSource)
          })
          this.reportList.params.forEach(item => {
            this.getDatrFn(item) // 拿到所有下拉菜单
          })
        }
      }
      this.lookIsShow = false
    },

    lookReport() {
      this.lookClicked = true
      const params = utils.mapToUrl(this.form) // 转码
      const url = `${process.env.VUE_APP_BASE_API}/report/print/${this.reportList.id}${params}`
      this.lookImg = url
      this.time = new Date().getTime()
      this.lookClicked = false
    },
    printFn() { // 打印
      const params = utils.mapToUrl(this.form) // 转码
      const url = `${process.env.VUE_APP_BASE_API}/report/print/${this.reportList.id}${params}`
      printJS({printable:url, type: 'pdf', header: 'My cool image header'})

    },
    exportFn() { // 导出
      this.exportClicked = true
      const params = utils.mapToUrl(this.form) // 转码
      const url = `${process.env.VUE_APP_BASE_API}/report/export/${this.reportList.id}${params}`
      window.open(url)
      this.exportClicked = false
    },
    reportTreeShow() {
      this.reportDialog = true
      templateList().then(res => {
        console.log(res)
        this.reportTree = res.data.data
      }).catch(err => { console.log(err) })
    },
    addReport() { // 添加报表
      this.addClicked = true
      const selectList = this.$refs.selectReport.getCheckedNodes()
      const ids = selectList.map(item => { return item.id })
      add(ids).then(res => {
        console.log(res, 'aaaa')
        this.this.reportDialog = false
        this.addClicked = false
      }).catch(() => {
        this.addClicked = false
        this.this.reportDialog = false
      })
    }
  }
}
</script>

<style scoped lang="scss">

</style>
